package com.goodboys.base.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

/**
 * Created by CJ on 2018-03-29.
 */
public class GoodboysException extends Exception{
    private final Logger logger = LoggerFactory.getLogger("goodboys");

    private String errorCode;       //错误编号
    private String errorMsg;        //错误详情

    public String getErrorMsg() {
        return errorMsg;
    }

    public String getErrorCode() {
        return errorCode;
    }

    public GoodboysException() {
        this.errorCode = GoodboysRespEnmu.FALT_UNKNOW.code();
        this.errorMsg = GoodboysRespEnmu.FALT_UNKNOW.msg();
    }

    public GoodboysException(String errorCode, String errorMsg) {
        this.errorCode = errorCode;
        this.errorMsg = errorMsg;
    }

    public GoodboysException(String errorCode, String errorMsg, Throwable t) {
        this(errorCode, errorMsg);this.initCause(t);
        if(StringUtils.isEmpty(errorMsg)) { this.errorMsg=t.getMessage();}
        else{this.errorMsg=errorMsg;}
        this.logMsg(errorCode,errorMsg,t);
    }

    public GoodboysException(Throwable t) {
        this(GoodboysRespEnmu.FALT_UNKNOW.code(),t.getMessage(),t);
    }

    public GoodboysException(GoodboysRespEnmu response) {
        this(response.code(), response.msg());
    }
    public GoodboysException(GoodboysRespEnmu response, Throwable t) {
        this(response.code(), response.msg(), t);
    }

    private void logMsg(String errorCode,String errorMsg,Throwable t){
        if(errorCode==null) {errorCode=this.errorCode;}
        if(errorMsg==null) {errorMsg=this.errorMsg;}
        String msg = "Catch GoodBoysException with code["+ errorCode +"],message["+ errorMsg +"] ";
        if(t!=null){
            String className = t.getStackTrace()[0].getClassName();
            int lineNum = t.getStackTrace()[0].getLineNumber();
            msg+=" in "+className+"["+ lineNum +"]";
            if(!StringUtils.isEmpty(t.getMessage())) {
                msg += ",cause by," + t.getMessage();
            }else{
                msg += ",cause by,NullPointerException!";
            }
            logger.error(msg);
        }
        if(t!=null) {logger.error(msg,t);}          //打印日志
        else {logger.error(msg);}                   //打印日志
    }

}
